﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Database;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>
    public partial class ABINFON : DocumentBase
    {
        #region-------------Properties-----------------------
        int ThreadCount = 0;
        int finishedcount = 0;
        int totalrecord = 0;
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public INTEXDataSet setUI;
        public INTEXDataSet setWorker=new INTEXDataSet();
        ABINFONData m_Data, m_DataX;
        public DataSet setResult;
        
        private DataRow dwUI;
        BackgroundWorker bgWorker;
        ABINFONReport m_rpt;
        ExcelX.ExcelLib.ExcelAgent m_exAgent;
        DataSet setANINFOR = new DataSet();
        DataTable tableUI;
        public ABINFON()
        {
            InitializeComponent();
            this.Name = "生产进度跟进";
            this.Title = "生产进度跟进";
            bgWorker = new BackgroundWorker();
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            
        }

        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {

            /*string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
            //链接Excel
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            //读取Excel里面有 表Sheet1
            OleDbDataAdapter oda = new OleDbDataAdapter("select * from 生产订单跟踪", cnnxls);
            DataSet ds = new DataSet();
            //将Excel里面有表内容装载到内存表中！
            oda.Fill(ds,2,2000,"ABPOS");
            DataTable dt = ds.Tables[0];
            return;
            */
         
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                base.SetUp(dicParamater);
                InitializeComponent();
               

                this.dicParamater = dicParamater;
                OracleDB = (OracleConnection)dicParamater["OracleDB"];
                proxy = (IntexReptServBLClient)dicParamater["proxy"];
                orlReadCommand = OracleDB.CreateCommand();
                orlReadCommand.Parameters.Add("OrdNum", OracleType.NVarChar).Value = "";
                m_Data = new ABINFONData(OracleDB,proxy);
                m_Data.OracleDB = this.OracleDB;
                m_Data.proxy = this.proxy;
                tableUI = new DataTable("UIData");
                tableUI.Columns.Add("ARTICLE", typeof(string));
                tableUI.Columns.Add("CUSTOMER", typeof(string));
                tableUI.Columns.Add("WBSRTDATE", typeof(string));
                tableUI.Columns.Add("WBENTDATE", typeof(string));
                tableUI.Columns.Add("VKDATE", typeof(string));
                //bgWorker.RunWorkerAsync();
               /* string filePath = @"C:\intex.w\Report\Planning\ABINFON.xls";
                if (System.IO.File.Exists(filePath))
                {
                    m_exAgent = new ExcelX.ExcelLib.ExcelAgent(filePath);
                    m_exAgent.iStart = 2;
                    int CurrentMaxColumns = 0;
                    m_exAgent.loadDataTableColumns("生产订单跟踪", ref CurrentMaxColumns, 100);
                    m_exAgent.ReadRangeValue2DataTable(3, 2000, 1, CurrentMaxColumns);
                    //m_exAgent.Load(filePath, 2000, 100);
                    filePath = filePath.Replace("ABINFON.xls", "ABINFON.XML");
                    m_exAgent.DataSource.WriteXml(filePath);
                }

                if (System.IO.File.Exists(filePath))
                {
                    setANINFOR.ReadXml(filePath);
                    setANINFOR.Tables[0].TableName = "ABPOS";
                    SndDg.DataContext = setANINFOR.Tables[0];
                }*/
                
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        } 
        #endregion

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                finishedcount = 0;
                setUI.Clear();
                zoneQueryCond.IsExpanded = false;
                setUI.AcceptChanges();
                //string ARTICLE = txtArticle.Text.Trim();
                string CUSTOMER = m_Data.Right("00000000" + txtCustomer.Text.Trim(), 8);

                dwUI["ARTICLE"] = txtArticle.Text.ToString().Trim();
                dwUI["CUSTOMER"] = CUSTOMER;
                string GISSUEStartDate = gsendstartdate.Text.ToString().Trim();
                string GISSUEEndDate = gsendenddate.Text.ToString().Trim();
                string OPENORDERDate = openorderdate.Text.ToString().Trim();
                string TODAY = DateTime.Now.Year.ToString() 
                    + m_Data.Right("00"+ DateTime.Now.Month.ToString(),2)
                    + m_Data.Right("00" + DateTime.Now.Day.ToString(), 2);
                if (GISSUEStartDate == "")
                {
                    GISSUEStartDate = "20000101";
                }
                if (GISSUEEndDate == "")
                {
                    GISSUEEndDate = "29990101";
                }
                if (OPENORDERDate == "")
                {
                    OPENORDERDate = TODAY;
                }
                dwUI["WBSRTDATE"] = GISSUEStartDate;
                dwUI["WBENTDATE"] = GISSUEEndDate;
                dwUI["VKDATE"] = OPENORDERDate;
                totalrecord = 0;
                using (new LongOperation(this, "读取符合条件的记录"))
                { 
                        setResult = m_Data.GetABPOS(dwUI);
                        setUI.Merge(setResult);
                        totalrecord = setUI.ABPOS.Rows.Count; 
                }
                foreach (DataRow dwNABPOS in setUI.ABPOS)
                { 
                    EventDispatcher.Instance.RaiseUIMessage("ABINFONData", dwNABPOS, OracleDB, proxy, setUI);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                dateChooser = (DatePicker)this.FindName("DateChooser");
                setUI = (INTEXDataSet)TryFindResource("iNTEXDataSet");
                //dwUIABPOS = setUI.ABPOS.NewRow();                
                if (setUI != null)
                {
                    //setResult = m_Data.GetWASTAMM();
                    setUI.Merge(setResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        } 
        public void ItemsControls_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {

                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;  
                     
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void Date_GotFocus(object sender, RoutedEventArgs e)
        {
             
        }
        private void gsendstartDateChooser_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
           gsendstartdate.Text= m_Data.GetDate(sender);
        }
        private void gsendendDateChooser_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
          gsendenddate.Text= m_Data.GetDate(sender);
        }
        private void btnReport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string PrintType = "JustExcel";
                GenerateReport(PrintType);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            string PrintType = "DirectPrint";
            GenerateReport(PrintType);
        }

        private void btnPrintPreview_Click(object sender, RoutedEventArgs e)
        {
            string PrintType = "OpenExcel";
            GenerateReport(PrintType);
        }
        public void GenerateReport(string PrintType)
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");

            // check to kill the right process
            /*foreach (Process ExcelProcess in AllProcesses)
            {
                ExcelProcess.Kill();
            }*/
            using (new LongOperation(this, "读取符合条件的记录"))
            {
                string VKPAUFNUM = "", FORDERNUM="";
                DataRow dwABINFON = null;
                bool flgNew = false;
                foreach (DataRow dwTemp in setUI.Tables[0].Rows)
                {
                    VKPAUFNUM = dwTemp["VKPAUFNUM"].ToString();
                    FORDERNUM = dwTemp["FORDERNUM"].ToString();
                    var query = from DataRow dwExist in setANINFOR.Tables[0].AsEnumerable()
                                where dwExist["VKPAUFNUM"].ToString() == VKPAUFNUM
                                && dwExist["FORDERNUM"].ToString() == FORDERNUM
                                select dwExist;
                    if (query.Count() > 0)
                    {
                        foreach (DataRow dwExist in query)
                        {
                            dwABINFON = dwExist;
                        }
                    }
                    else
                    {
                        dwABINFON = setANINFOR.Tables[0].NewRow();
                        flgNew = true;
                    }
                    foreach (DataColumn dcTemp in dwABINFON.Table.Columns)
                    {
                        string column = dcTemp.ColumnName;
                        if (dwTemp.Table.Columns.Contains(column.Trim()))
                        {
                            dwABINFON[column] = dwTemp[column.Trim()];
                        }
                    }
                    if (flgNew)
                    {
                        flgNew = false;
                        setANINFOR.Tables[0].Rows.Add(dwABINFON);
                    }
                }
                m_DataX = new ABINFONData(dicParamater);
                m_DataX.exAgent._app.Visible = false;
                m_DataX.OracleDB = this.OracleDB;
                m_DataX.proxy = this.proxy;
                m_rpt = new ABINFONReport(dicParamater);
                m_rpt.dsSource = setANINFOR;
                m_rpt.PrintType = PrintType;
                m_rpt.exAgent = m_DataX.exAgent;
                m_rpt.WriteExcelReport("EXCEL");
            }
        }
         
        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;
            //tb.Text = "";
        }

        private void openorderDateChooser_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            openorderdate.Text = m_Data.GetDate(sender);
        }
    }
}
